package com.softWang.common.service.sms.tencent;

import com.softWang.common.exception.LogicException;
import com.softWang.common.service.sms.SmsSendInterface;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component("tencentSmsSendImpl")
@ConditionalOnProperty(name = "sms.impl", havingValue = "tencentSmsSendImpl")
public class TencentSmsSendImpl implements SmsSendInterface {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private TencentConfig tencentConfig;


    private SmsClient smsClient;

    @PostConstruct
    public void init(){
        try {
            // 实例化认证对象
            Credential cred = new Credential(tencentConfig.getSecretID(), tencentConfig.getSecretKey());

            // 实例化HTTP选项
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(tencentConfig.getEndpoint());

            // 实例化客户端配置
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            this.smsClient = new SmsClient(cred, tencentConfig.getRegion(), clientProfile);
            logger.info("初始化腾讯云短信服务成功");
        }catch (Exception e){
            logger.error("初始化腾讯云短信服务失败:",e);
        }
    }
    @Override
    public void sendSms(String mobile, String templateCode, LinkedHashMap<String, Object> templateParam) throws TencentCloudSDKException {
        SendSmsRequest req = new SendSmsRequest();
        // 设置短信应用ID
        req.setSmsSdkAppId(tencentConfig.getAppId());
        // 设置签名名称
        req.setSignName(tencentConfig.getSignName());
        // 设置模板ID
        req.setTemplateId(templateCode);
        // 设置模板参数
        String[] templateParams = templateParam.values().toArray(new String[0]);
        req.setTemplateParamSet(templateParams);

        // 设置手机号（需要带国际区号，如+86）
        String[] phoneNumberSet = new String[]{"+86" + mobile};
        req.setPhoneNumberSet(phoneNumberSet);

        SendSmsResponse response= smsClient.SendSms(req);
        if (!"Ok".equals(response.getSendStatusSet()[0].getCode())) {
            logger.error("腾讯短信发送失败，错误码：" + response.getSendStatusSet()[0].getCode() + "，错误信息：" + response.getSendStatusSet()[0].getMessage());
            throw new LogicException("腾讯短信发送失败，错误码：" + response.getSendStatusSet()[0].getCode() + "，错误信息：" + response.getSendStatusSet()[0].getMessage());
        }
    }

    @Override
    public void sendSmsBatch(List<String> mobiles, String templateCode, LinkedHashMap<String, Object> templateParam) throws Exception {
        SendSmsRequest req = new SendSmsRequest();
        // 设置短信应用ID
        req.setSmsSdkAppId(tencentConfig.getAppId());
        // 设置签名名称
        req.setSignName(tencentConfig.getSignName());
        // 设置模板ID
        req.setTemplateId(templateCode);
        // 设置模板参数
        String[] templateParams = templateParam.values().toArray(new String[0]);
        req.setTemplateParamSet(templateParams);

        // 添加国际区号
        String[] formattedNumbers = new String[mobiles.size()];
        for (int i = 0; i < mobiles.size(); i++) {
            formattedNumbers[i] = "+86" + mobiles.get(i);
        }
        req.setPhoneNumberSet(formattedNumbers);

        SendSmsResponse response= smsClient.SendSms(req);

        if (!"Ok".equals(response.getSendStatusSet()[0].getCode())) {
            logger.error("腾讯短信批量发送失败，错误码：" + response.getSendStatusSet()[0].getCode() + "，错误信息：" + response.getSendStatusSet()[0].getMessage());
            throw new LogicException("腾讯短信批量发送失败，错误码：" + response.getSendStatusSet()[0].getCode() + "，错误信息：" + response.getSendStatusSet()[0].getMessage());
        }
    }
}
